package com.party.admin.web.controller.crowdfund;

import com.party.admin.biz.crowdfund.TargetBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.output.activity.ActivityOutput;
import com.party.common.constant.Constant;
import com.party.common.utils.DateUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityDetail;
import com.party.core.model.activity.CrowfundResources;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.notify.TargetTemplate;
import com.party.core.model.notify.TargetTemplateType;
import com.party.core.service.activity.IActivityDetailService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.ICrowfundResourcesService;
import com.party.core.service.activity.biz.ActivityDetailBizService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ITargetTemplateService;
import com.party.core.service.member.IMemberGroupService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 众筹项目控制器
 * Created by wei.li
 *
 * @date 2017/7/4 0004
 * @time 11:00
 */

@Controller
@RequestMapping(value = "/crowdfund/target")
public class TargetController {


    @Autowired
    private TargetBizService targetBizService;
    
    @Autowired
    private IActivityService activityService;

    @Autowired
    private ITargetTemplateService targetTemplateService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private ICrowfundResourcesService crowfundResourcesService;

    @Autowired
    private IActivityDetailService activityDetailService;

    @Autowired
    private ActivityDetailBizService activityDetailBizService;

    @Autowired
    private ICounterfoilService counterfoilService;

    @Autowired
    private IMemberGroupService memberGroupService;

    protected static Logger logger = LoggerFactory.getLogger(TargetController.class);
    /**
     * 消息发送视图
     * @param targetId 项目编号
     * @return 交互数据
     */
    @RequestMapping(value = "messageView")
    public ModelAndView messageView(String targetId, Integer type, String id, String behavior){
        ModelAndView modelAndView = new ModelAndView("crowdfund/messageView");
        TargetTemplate targetTemplate = null;

        if ("add".equals(behavior)) {
            targetTemplate = targetTemplateService.recently(targetId, type);
            if (null == targetTemplate){
                targetTemplate = new TargetTemplate();
                targetTemplate.setTargetId(targetId);
                targetTemplate.setType(type);
            }
        } else {
            targetTemplate = targetTemplateService.get(id);
        }
        Map<Integer, String> types = TargetTemplateType.convertMap(0);

        for (Map.Entry<Integer, String> entry : types.entrySet()) {
            Integer status = null;
            if (TargetTemplateType.CROWDFUND_SUCCESS.getCode().equals(entry.getKey())){
                status = Constant.IS_CROWFUND_SUCCESS;
            }
            else if (TargetTemplateType.CROWDFUND_UNDERWAY.getCode().equals(entry.getKey())){
                status = Constant.IS_CROWFUND_ING;
            }
            else if (TargetTemplateType.CROWDFUNF_ALL.getCode().equals(entry.getKey())){
                status = null;
            }
            Integer num = projectService.countByActivity(targetId, status);
            entry.setValue(entry.getValue() + "(" + num + "人)");
        }

        modelAndView.addObject("types", types);
        modelAndView.addObject("behavior", behavior);
        modelAndView.addObject("targetTemplate", targetTemplate);
        return modelAndView;
    }


    /**
     * 消息推送
     * @param targetTemplate 目标模板
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "saveCrowdfund")
    public AjaxResult saveCrowdfund(TargetTemplate targetTemplate){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            targetBizService.sendAndSave(targetTemplate);
        }
        catch (BusinessException be){
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            logger.error("消息推送异常", be);
            return ajaxResult;
        }
        catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("发送异常");
            logger.error("消息推送异常", e);
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    /**
     * 众筹短信主动推送
     * @param id 众筹模板编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "sendCrowdfund")
    public AjaxResult sendCrowdfund(String id){
        AjaxResult ajaxResult = new AjaxResult(true);
        try {
            targetBizService.send(id);
        } catch (Exception e) {
            logger.error("众筹短信主动推送异常", e);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("众筹短信主动推送异常");
            return ajaxResult;
        }
        return ajaxResult;
    }

    /**
     * 消息推送-定时
     * @param targetTemplate
     * @param sendTimeString: 格式为yyyy-MM-dd HH:mm:ss
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "sendQuartz")
    public AjaxResult sendQuartz(TargetTemplate targetTemplate, String sendTimeString, String behavior) {
        try {
            return targetBizService.sendQuartz(targetTemplate, sendTimeString, behavior, Constant.SEND_SHORT_MESSAGE_TYPE_CROWDFUN_PROJECT);
        } catch (Exception e) {
            logger.error("定时短信推送异常", e);
            return AjaxResult.error("定时短信推送异常");
        }
    }

    /**
     * 删除短信
     * @param id: 模板id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delQuartz")
    public AjaxResult delQuartz(String id) {
        try {
            return targetBizService.delQuartz(id);
        } catch (Exception e) {
            logger.error("删除定时短信异常", e);
            return AjaxResult.error("定时短信删除异常");
        }
    }

    /**
     * 消息推送-定时-众筹事件
     * @param targetTemplate
     * @param sendTimeString: 格式为yyyy-MM-dd HH:mm:ss
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "sendQuartzForEvent")
    public AjaxResult sendQuartzForEvent(TargetTemplate targetTemplate, String sendTimeString, String behavior) {
        try {
            return targetBizService.sendQuartz(targetTemplate, sendTimeString, behavior, Constant.SEND_SHORT_MESSAGE_TYPE_Event);
        } catch (Exception e) {
            logger.error("定时短信推送异常", e);
            return AjaxResult.error("定时短信推送异常");
        }
    }

    /**
     * 复制众筹
     * @param id 编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "copy")
    public AjaxResult copy(String id){
        AjaxResult ajaxResult = new AjaxResult();
        targetBizService.copy(id);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    /**
     * 复制众筹视图
     * @param id 编号
     * @return 交互数据
     */
    @RequestMapping(value = "copyView")
    public ModelAndView copyView(String id, HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView("activity/zcActivityFormNew");
        if (StringUtils.isNotEmpty(id)) {
            //活动
            Activity activity = activityService.get(id);
            ActivityOutput activityOutput = ActivityOutput.transform(activity);
            activityOutput.setId(null);
            activityOutput.setCreateDate(DateUtils.getTodayDate());
            activityOutput.setUpdateDate(DateUtils.getTodayDate());
            activityOutput.setBeCrowdfundNum(0);
            activityOutput.setCrowdfundedNum(0);
            activityOutput.setJoinNum(0);
            activityOutput.setShareNum(0);
            activityOutput.setReadNum(0);
            activityOutput.setGoodNum(0);
            activityOutput.setFavorerNum(0);
            activityOutput.setRepresentNum(0);

            String address = activityService.getShowAddress(activity);
            modelAndView.addObject("address", address);

            // 跑马灯
            List<CrowfundResources> picList = crowfundResourcesService.findByRefId(activity.getId(), "1");
            modelAndView.addObject("picList", picList);

            // 视频
            List<CrowfundResources> videoList = crowfundResourcesService.findByRefId(activity.getId(), "2");
            if (videoList.size() > 0) {
                modelAndView.addObject("video", videoList.get(0));
            }

            //活动详情
            ActivityDetail activityDetail = activityDetailService.getByRefId(activity.getId());
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }

            MemberGroup createBy = memberGroupService.get(activity.getMember());
//            if (YesNoStatus.YES.getCode().equals(activity.getIsCopartner())) {
//                TargetCopartner targetCopartner = targetCopartnerService.findByTargetId(activity.getId());
//                modelAndView.addObject("targetCopartner", targetCopartner);
//            }
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
            modelAndView.addObject("crowdfundEvent", crowdfundEvent);
            modelAndView.addObject("createBy", createBy);
            modelAndView.addObject("activityDetail", activityDetail);
            modelAndView.addObject("activity", activityOutput);

            List<Counterfoil> counterfoils = counterfoilService.findByBusinessId(crowdfundEvent.getId(), Constant.BUSINESS_TYPE_CROWDFUND);
            modelAndView.addObject("counterfoils", counterfoils);
        } else {
            CrowdfundEvent crowdfundEvent = new CrowdfundEvent();
            crowdfundEvent.setProgress(YesNoStatus.YES.getCode()); // 进行中
            List<CrowdfundEvent> crowdfundEventList = crowdfundEventService.list(crowdfundEvent);
            modelAndView.addObject("crowdfundEventList", crowdfundEventList);
        }
        return modelAndView;
    }

    /**
     * 事项消息发送视图
     * @param targetId 项目编号
     * @return 交互数据
     */
    @RequestMapping(value = "messageViewForEvent")
    public ModelAndView messageViewForEvent(String targetId, Integer type, String id, String behavior){
        ModelAndView modelAndView = new ModelAndView();
        TargetTemplate targetTemplate = null;

        if ("add".equals(behavior)) {
            targetTemplate = targetTemplateService.recently(targetId, type);
            if (null == targetTemplate){
                targetTemplate = new TargetTemplate();
                targetTemplate.setTargetId(targetId);
                targetTemplate.setType(type);
            }
        } else {
            targetTemplate = targetTemplateService.get(id);
        }
        Map<Integer, String> types = TargetTemplateType.convertMap(0);

        for (Map.Entry<Integer, String> entry : types.entrySet()) {
            Integer status = null;
            if (TargetTemplateType.CROWDFUND_SUCCESS.getCode().equals(entry.getKey())){
                status = Constant.IS_CROWFUND_SUCCESS;
            }
            else if (TargetTemplateType.CROWDFUND_UNDERWAY.getCode().equals(entry.getKey())){
                status = Constant.IS_CROWFUND_ING;
            }
            else if (TargetTemplateType.CROWDFUNF_ALL.getCode().equals(entry.getKey())){
                status = null;
            }
            Integer num = projectService.countByEvent(targetId, status);
            entry.setValue(entry.getValue() + "(" + num + "人)");
        }

        modelAndView.addObject("types", types);
        modelAndView.addObject("targetTemplate", targetTemplate);
        modelAndView.addObject("behavior", behavior);
        modelAndView.setViewName("crowdfund/messageViewForEvent");
        return  modelAndView;
    }


    /**
     * 保存事项模板
     * @param targetTemplate 事项模板
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "saveForEvent")
    public AjaxResult saveForEvent(TargetTemplate targetTemplate){
        AjaxResult ajaxResult = new AjaxResult(true);
        try {
            targetBizService.sendAndSaveForEvent(targetTemplate);
        } catch (BusinessException be){
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("保存事项模板异常", e);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("保存事项模板异常");
            return ajaxResult;
        }
        return ajaxResult;
    }


    /**
     * 消息推送
     * @param id 目标模板编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "sendForEvent")
    public AjaxResult sendForEvent(String id){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            targetBizService.sendForEvent(id);
        }
        catch (BusinessException be){
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("事项消息推送异常");
            logger.error("事项消息推送异常", be);
            return ajaxResult;
        }
        catch (Exception e) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("发送异常");
            logger.error("消息推送异常", e);
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }
}
